#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc,char* argv[])
{
  int tcp_fd = socket(AF_INET,SOCK_STREAM,0);
  if(tcp_fd < 0)
  {
    perror("socket fail");
    exit(-1);
  }

  struct sockaddr_in server_addr;
  server_addr.sin_port = htons(50000);
  server_addr.sin_family = AF_INET;
  inet_pton(AF_INET,"0.0.0.0",&server_addr.sin_addr);

  int ret = bind(tcp_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
  if(ret < 0)
  {
    perror("bind fail");
    return -1;
  }

  printf("wait for process \n");
  int on = 1; // 写一，表示启用

  setsockopt(tcp_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  listen(tcp_fd,1);

  struct sockaddr_in client_addr;
  socklen_t len = sizeof(client_addr);
  int con_fd = accept(tcp_fd,(struct sockaddr*)&client_addr,&len);
  if(con_fd < 0)
  {
    perror("accept fail");
    return -1;
  }

  printf("prot:%d\n", ntohs(client_addr.sin_port));
  printf("id:%s\n",inet_ntoa(client_addr.sin_addr));

  char buf[1024] = {0};
  
  while(1)
  {
    read(con_fd,buf,1024);
    printf("read is %s\n",buf);
    if(!strcmp(buf,"bye"))
      break;
  }

  
  close(con_fd);
  close(tcp_fd);
  return 0;
}
